package com.jzg.jcptadmin.presenter;

import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.jzg.jcptadmin.Utils.BitmapUtils;
import com.jzg.jcptadmin.Utils.ImgUtils;
import com.jzg.jcptadmin.Utils.ScreenUtils;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.base.BasePresenter;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.local.LocalData;
import com.jzg.jcptadmin.data.vo.ImageItem;
import com.jzg.jcptadmin.data.vo.ImageList;
import com.jzg.jcptadmin.data.vo.UpLoadImageData;
import com.jzg.jcptadmin.viewinterface.AddTaskActivityInterface;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by jzg on 2015/12/24.
 */
public class AddTaskPresenter extends BasePresenter<AddTaskActivityInterface> {
    public static ImageList imageList;
    public static ImageItem item;
    private AppContext appContext;
    public List<ImageItem> lists;
    private DataManager mDataManager;

    private Subscription mSubscription;

    public AddTaskPresenter(AppContext appContext, DataManager instance) {
        this.appContext = appContext;
        imageList = (ImageList) ACache.get(appContext).getAsObject("imagecache");
        if (imageList == null) {
            imageList = new ImageList(initPic());
        } else {
            if (imageList.getLists().size() > 18) {
                ACache.get(appContext).remove("imagecache");
                imageList = new ImageList(initPic());
            }
        }
        lists = imageList.getLists();
        mDataManager = instance;
    }


    public ArrayList<ImageItem> initPic() {
        ArrayList<ImageItem> items = new ArrayList<>();
        for (String string : LocalData.names) {
            items.add(new ImageItem(string));
        }
        return items;
    }

    public void toTop() {
        mSubscription = Observable.timer(100, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.
                mainThread()).subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                getMvpView().toTop();
            }
        });
    }

    /**
     * 从相机或者图库添加照片
     */
    public void addPic(final String picPath, final int position, final String carid, final String itemid) {
//        final String[] url = new String[1];
        mSubscription = Observable.create(new Observable.OnSubscribe<ImageItem>() {
            @Override
            public void call(Subscriber<? super ImageItem> subscriber) {
                try {
                    //保存图片到系统内容提供器
//                    url[0] = MediaStore.Images.Media.insertImage(appContext.getContentResolver(),
//                            picPath, null, null);
                    //创建大图存放路径
                    String bigPicPath = createBigPicPath();
                    //创建缩略图存放路径
                    String tubPicPath = createTubPicPath();
                    //保存大图
                    BitmapUtils utils = new BitmapUtils();
                    boolean isBigPicSave = utils.saveImage(picPath, bigPicPath);
                    //保存缩略图
                    boolean isTubPicSave = utils.saveImage(ImgUtils.getImageThumbnail(bigPicPath, ScreenUtils.dip2px(appContext, 85),ScreenUtils.dip2px(appContext, 70)), tubPicPath);
                    if (!subscriber.isUnsubscribed() && isBigPicSave && isTubPicSave) {
                        item = new ImageItem(bigPicPath, tubPicPath, position);
                        subscriber.onNext(item);
                    }
                } catch (Exception e) {
                    if (!subscriber.isUnsubscribed())
                        subscriber.onError(e);
                }
            }
        }).subscribe(new Observer<ImageItem>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (e != null&&getMvpView()!=null) {
                    getMvpView().showError(e.getMessage());
                }
            }

            @Override
            public void onNext(ImageItem imageItem) {
                upLoadImage(imageItem, carid, itemid);
            }
        });

    }

    /**
     * 创建缩略图文件的存放地址
     *
     * @return
     */
    private String createTubPicPath() {
        return createPicPath("/JZGErShouChe/photo_tub");
    }

    /**
     * 创建大图文件的存放地址
     *
     * @return
     */
    private String createBigPicPath() {
        return createPicPath("/JZGErShouChe/photo_temp");
    }

    /**
     * 创建图片存放地址
     *
     * @param path
     * @return
     */
    private String createPicPath(String path) {
        File dirFile = new File(Environment.getExternalStorageDirectory().getPath()
                + path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        // 格式化时间
        String dataTake = new SimpleDateFormat(
                "yyyyMMddHHmmssSSS").format(new Date());
        return dirFile.getPath() + File.separator + dataTake + ".jpg";
    }

    public void upLoadImage(final ImageItem s, String carid, String itemid) {
        if (appContext.isNetWork)
            mSubscription = mDataManager.UploadImage(s.getImagePath(), itemid, carid)
                    .observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                    .subscribe(new Observer<UpLoadImageData>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            if (e != null)
                                getMvpView().showError(e.getMessage());
                        }

                        @Override
                        public void onNext(UpLoadImageData upLoadImageData) {
                            getMvpView().backByPhoto(upLoadImageData);

                        }
                    });
    }


    /**
     * 根据Uri获取图片绝对路径 uri2Path
     *
     * @param @param  uri
     * @param @return
     * @return String
     * @throws
     * @Title: uri2Path
     * @Description: TODO
     */
    public String uri2Path(Uri uri) {
        int actual_image_column_index;
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = appContext.getContentResolver().query(uri, proj, null, null, null);
        actual_image_column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        img_path = cursor.getString(actual_image_column_index);
        return img_path;
    }

    @Override
    public void detachView() {
        super.detachView();
        if (mSubscription != null)
            mSubscription.unsubscribe();
    }

}
